package com.touzhijia.authority.service;

import com.touzhijia.authority.domain.dto.request.AuthenticationReq;
import com.touzhijia.authority.domain.dto.request.AuthorizationReq;
import com.touzhijia.authority.domain.dto.response.AuthenticationRes;
import com.touzhijia.authority.domain.dto.response.AuthorizationRes;
import com.touzhijia.authority.domain.dto.response.UserRes;
import com.touzhijia.authority.domain.entity.Permission;
import com.touzhijia.authority.domain.entity.Role;
import com.touzhijia.authority.domain.entity.User;
import com.touzhijia.authority.mapper.PermissionMapper;
import com.touzhijia.authority.mapper.RoleMapper;
import com.touzhijia.authority.mapper.UserMapper;
import com.touzhijia.authority.model.LdapUser;
import com.touzhijia.authority.repository.LdapUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-03-24 14:41 <br/>
 */
@Transactional(readOnly = true)
@Service
@Slf4j
public class AuthorityService {

    /**
     * 认证服务域名
     */
    private static final String LDAP_DOMAIN = "@touzhijia.net";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private LdapUserRepository ldapUserRepository;
    @Autowired
    private ContextSource contextSource;

    public List<Role> findUserAllRole(String username) {
        return roleMapper.findUserAllRole(username);
    }

    public List<Permission> findUserAllPermission(String username) {
        return permissionMapper.findUserAllPermission(username);
    }

    public List<Permission> findUserAllPermission(String username, String module) {
        return permissionMapper.findUserAllPermissionByModule(username, module);
    }

    public AuthenticationRes authentication(String module, AuthenticationReq authenticationReq) {
        AuthenticationRes authenticationRes = new AuthenticationRes(false, "登录失败");
        User user = userMapper.getByUsername(authenticationReq.getUsername());
        if (user == null) {
            authenticationRes.setMessage("用户不存在");
            return authenticationRes;
        }
        switch (user.getUserType()) {
            case User.User_Type_0:
                // TODO 暂不支持自定义用户登录
                authenticationRes.setMessage("暂不支持自定义用户登录");
                return authenticationRes;
            case User.User_Type_1:
                // 验证用户登录
                try {
                    LdapQuery ldapQuery = LdapQueryBuilder.query().filter("(sAMAccountName=" + authenticationReq.getUsername() + ")");
                    LdapUser ldapUser = ldapUserRepository.findOne(ldapQuery);
                    if (ldapUser == null) {
                        authenticationRes.setMessage("用户不存在");
                        return authenticationRes;
                    }
                    contextSource.getContext(authenticationReq.getUsername() + LDAP_DOMAIN, authenticationReq.getPassword()).close();
                } catch (Throwable e) {
                    authenticationRes.setMessage("用户名密码错误");
                    return authenticationRes;
                }
                break;
            default:
                authenticationRes.setMessage("用户类型错误");
                return authenticationRes;
        }
        if (module != null) {
            int count = userMapper.existsModule(authenticationReq.getUsername(), module);
            if (count <= 0) {
                authenticationRes.setMessage("登录失败，请联系管理员授权登录此系统");
                return authenticationRes;
            }
        }
        authenticationRes.setSuccess(true);
        authenticationRes.setMessage("登录成功");
        UserRes userRes = new UserRes();
        userRes.setUsername(user.getUsername());
        userRes.setNickname(user.getNickname());
        userRes.setTelephone(user.getTelephone());
        userRes.setEmail(user.getEmail());
        userRes.setMemberOf(user.getMemberOf());
        userRes.setUserType(user.getUserType());
        authenticationRes.setUser(userRes);
        return authenticationRes;
    }

    public AuthorizationRes authorization(AuthorizationReq authorizationReq) {
        AuthorizationRes authorizationRes = new AuthorizationRes(false, "授权失败");
        User user = userMapper.getByUsername(authorizationReq.getUsername());
        if (user == null) {
            authorizationRes.setMessage("用户不存在");
            return authorizationRes;
        }
        int count = permissionMapper.existsPermissionByUser(authorizationReq.getUsername(), authorizationReq.getPermission());
        if (count <= 0) {
            authorizationRes.setMessage("授权失败，未授权");
            return authorizationRes;
        }
        authorizationRes.setSuccess(true);
        authorizationRes.setMessage("授权成功");
        return authorizationRes;
    }

    public List<Permission> findAllPermission() {
        return permissionMapper.selectAll();
    }

    public List<Permission> findAllPermission(String module) {
        return permissionMapper.findPermissionByModule(module);
    }
}
